package dry.example.parse;

import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.body.VariableDeclarator;
import com.github.javaparser.ast.expr.NameExpr;
import com.github.javaparser.ast.expr.SimpleName;
import com.github.javaparser.ast.expr.VariableDeclarationExpr;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.TreeSet;

/**
 * @author zc
 */
public class Tool {

    /**
     * 重命名标识符
     *
     * @param methodDeclaration 方法申明
     * @param parameter         参数
     */
    public static void rename(MethodDeclaration methodDeclaration, Parameter parameter) {
        //把标识符排序后存起来
        TreeSet<String> set = new TreeSet<>();
        //set转list方便知道标识符的排序数字
        List<String> sortList;
        //最后统一修改标识符
        List<SimpleName> list = new ArrayList<>();
        //标识符->顺序
        HashMap<String, Integer> map = new HashMap<>(16);
        //标识符声明的语句
        List<VariableDeclarator> variableDeclaratorList = methodDeclaration.findAll(VariableDeclarator.class);
        for (VariableDeclarator variableDeclarator : variableDeclaratorList) {
            SimpleName simpleName = variableDeclarator.getName();
            String identifier = simpleName.getIdentifier();
            set.add(identifier);
            list.add(simpleName);
        }
        //标识符声明的语句
        List<VariableDeclarationExpr> variableDeclarationExprList = methodDeclaration.findAll(VariableDeclarationExpr.class);
        for (VariableDeclarationExpr variableDeclarationExpr : variableDeclarationExprList) {
            NodeList<VariableDeclarator> nodeList = variableDeclarationExpr.getVariables();
            for (VariableDeclarator variableDeclarator : nodeList) {
                SimpleName simpleName = variableDeclarator.getName();
                String identifier = simpleName.getIdentifier();
                set.add(identifier);
                list.add(simpleName);
            }
        }
        //标识符使用的语句
        List<NameExpr> nameExprList = methodDeclaration.findAll(NameExpr.class);
        for (NameExpr nameExpr : nameExprList) {
            SimpleName simpleName = nameExpr.getName();
            //不能把标识符加入set
            list.add(simpleName);
        }
        sortList = new ArrayList<>(set);
        for (int i = 0; i < sortList.size(); i++) {
            map.put(sortList.get(i), i);
        }
        for (SimpleName simpleName : list) {
            String identifier = simpleName.getIdentifier();
            if (!map.containsKey(identifier)) {
                continue;
            }
            int sort = map.get(identifier);
            simpleName.setIdentifier(parameter.getRepeat().repeat(sort + 1));
        }
    }

}
